package com.woodws.core.util;

import com.woodws.core.service.Message;
import com.woodws.util.FieldUtil;
import org.springframework.web.context.WebApplicationContext;

import java.util.Map;

/**
 * Created by maoxiaodong on 2016/11/1.
 */

public class I18nUtil {

    public I18nUtil(WebApplicationContext context) {
        setMessage(context);
    }

    private Message message;

    public void escapeLanguage(Object object, String attrs) {
        String attr = attrs;
        int index = attr.indexOf(".");
        if (index == -1) {
            if (object instanceof Map) {
                Map map = (Map) object;
                String value = map.get(attr).toString();
                map.put(attr, message.get(value));
            } else {
                String value = FieldUtil.getValue(object, attr);
                FieldUtil.setValue(object, attr, message.get(value));
            }
        } else {
            attr = attrs.substring(0, index);
            attrs = attrs.substring(index + 1, attrs.length());
            Object obj;
            if (object instanceof Map) {
                Map map = (Map) object;
                obj = map.get(attr);
            } else {
                obj = FieldUtil.getValue(object, attr);
            }
            escapeLanguage(obj, attrs);
        }
    }

    public void setMessage(WebApplicationContext context) {
        message = context.getBean(Message.class);
    }
}
